/*******************************************************************
This file is part of iAgenda.

iAgenda is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

iAgenda is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with iAgenda.  If not, see <http://www.gnu.org/licenses/>.
*******************************************************************/

#include "stdafx.h"
#include "FileUtils.h"
//#include "Macros.h"

bool bSet; //ajige 3/31/10

// Thanks l3v5y!  ajige 3/31/10 will use button for settings instead which should be in same directory
/*bool GetIDialerFilename(TCHAR * szFilename) {

	HKEY hkey;

    // Where app install data is stored
	LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
        TEXT("Software\\Apps\\Supware.net iDialer"), 0, 
		KEY_QUERY_VALUE, &hkey);

    // Try to find iDialer from installation in registry
    if (0 == result) {
		DWORD buffersize = MAX_PATH;
		RegQueryValueEx(hkey, TEXT("InstallDir"), NULL, NULL,
            (PBYTE)szFilename, &buffersize);
		RegCloseKey(hkey);
	}

    // Otherwise, assume it's stored in the same location
    // (either both in memory or both on storage card)
	else {
        // generate path name for iAgenda
        ::GetModuleFileName(NULL, szFilename, MAX_PATH);
        TCHAR * pstr = _tcsrchr(szFilename, '\\');
        if (pstr) *(pstr) = '\0';

        // Go "up 1" directory. We should then be in \Program Files
        pstr = _tcsrchr(szFilename, '\\');
        if (pstr) *(++pstr) = '\0';

        // Concatenate iDialer program directory
        StringCchCat(szFilename, MAX_PATH, TEXT("iDialer"));
	}

    // Concatenate iDialer exe path
	StringCchCat(szFilename, MAX_PATH, TEXT("\\iDialer.exe"));

	return FileExists(szFilename);
}*/

bool FileExists(const TCHAR * szFilename) {
	// test if file exists
	HANDLE h = CreateFile(szFilename, GENERIC_READ,
		FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, NULL, NULL);
	bool exists = h != INVALID_HANDLE_VALUE;
	if (exists)
		CloseHandle(h);
	return exists;
}

bool GetISettingsFilename(TCHAR * szFilename) {
//ajige 2/12/10 TODO change this to open settings file
	HKEY hkey;
	//MessageBox(0, L"GetISettingsFilename", L"Hei", 0);
	// Where app install data is stored
	LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
		TEXT("Software\\Apps\\Supware.net iAgenda"), 0, 
		KEY_QUERY_VALUE, &hkey);

	// Try to find iDialer from installation in registry
	if (0 == result) {
		DWORD buffersize = MAX_PATH;
		RegQueryValueEx(hkey, TEXT("InstallDir"), NULL, NULL,
			(PBYTE)szFilename, &buffersize);
		RegCloseKey(hkey);
	}

	// Otherwise, assume it's stored in the same location
	// (either both in memory or both on storage card)
	else {
		// generate path name for iAgenda
		::GetModuleFileName(NULL, szFilename, MAX_PATH);
		TCHAR * pstr = _tcsrchr(szFilename, '\\');
		if (pstr) *(pstr) = '\0';

		// Go "up 1" directory. We should then be in \Program Files
		pstr = _tcsrchr(szFilename, '\\');
		if (pstr) *(++pstr) = '\0';

		// Concatenate iDialer program directory
		//ajige 3/31/10 StringCchCat(szFilename, MAX_PATH, TEXT("iContact"));
	}

	// Concatenate iDialer exe path
	StringCchCat(szFilename, MAX_PATH, TEXT("\\Settings.exe"));
//MessageBox(0, szFilename, L"Hei", 0);
	return FileExists(szFilename);
}


void GetCurDirFilename(TCHAR * szFilename, const TCHAR * filename, 
                       const TCHAR * extension) {

    ::GetModuleFileName(NULL, szFilename, MAX_PATH);
    TCHAR * pstr = _tcsrchr(szFilename, '\\');
    if (pstr) *(++pstr) = '\0';
    StringCchCat(szFilename, MAX_PATH, filename);
    if (extension != NULL) {
        StringCchCat(szFilename, MAX_PATH, TEXT("."));
        StringCchCat(szFilename, MAX_PATH, extension);
    }
}

// *************************************************
// Date/time Utility functions
// *************************************************

// http://www.hermetic.ch/cal_stud/jdn.htm
//UINT _getDaySerial(const SYSTEMTIME * st) {
//	int y = st->wYear;
//	int m = st->wMonth;
//	int d = st->wDay;
//	
//	// we'll modify the official julian date to instead be
//	// "days elapsed since Jan 1, 1995" (since that's a sunday)
//	long jul = ( 1461 * ( y + 4800 + ( m - 14 ) / 12 ) ) / 4 +
//		( 367 * ( m - 2 - 12 * ( ( m - 14 ) / 12 ) ) ) / 12 -
//		( 3 * ( ( y + 4900 + ( m - 14 ) / 12 ) / 100 ) ) / 4 +
//		d - 32075 - 2449719;
//
//	return jul;
//}

// http://www.hermetic.ch/cal_stud/jdn.htm
//void _fillSystemTimeFromSerial(SYSTEMTIME * st, UINT userial) {
//	UINT jd = userial + 2449719;
//	UINT l, n, i, j, d, m, y;
//
//	l = jd + 68569;
//	n = ( 4 * l ) / 146097;
//	l = l - ( 146097 * n + 3 ) / 4;
//	i = ( 4000 * ( l + 1 ) ) / 1461001;
//	l = l - ( 1461 * i ) / 4 + 31;
//	j = ( 80 * l ) / 2447;
//	d = l - ( 2447 * j ) / 80;
//	l = j / 11;
//	m = j + 2 - ( 12 * l );
//	y = 100 * ( n - 49 ) + i + l;
//
//	st->wHour = 0;
//	st->wMinute = 0;
//	st->wSecond = 0;
//	st->wDayOfWeek = 0;
//	st->wYear = y;
//	st->wMonth = m;
//	st->wDay = d;
//}

//UINT _getPastTime(FILETIME ftTime, TCHAR * pszSecondary, int strLength) {
//	FILETIME ftLocal;
//	SYSTEMTIME st;
//
//	// if ftTime somehow == 0, then get outta here
//	if (!ftTime.dwHighDateTime && !ftTime.dwLowDateTime) {
//		if (pszSecondary)
//			pszSecondary[0] = 0;
//		return 0;
//	}
//
//	FileTimeToLocalFileTime(&ftTime, &ftLocal);
//	FileTimeToSystemTime(&ftLocal, &st);
//	UINT u = _getDaySerial(&st);
//
//	if (pszSecondary)
//		::GetTimeFormat(LOCALE_USER_DEFAULT, 
//		TIME_NOSECONDS, &st,
//		NULL, pszSecondary, strLength);
//
//	return u;
//}

// prints the date and time, like: 2008/04/02 23:59
// in the user's current locale
//void _printDate(TCHAR * str, int strLength, FILETIME ft) {
//	FILETIME ftLocal;
//	SYSTEMTIME st;
//
//	FileTimeToLocalFileTime(&ft, &ftLocal);
//	FileTimeToSystemTime(&ftLocal, &st);
//	::GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
//		NULL, str, strLength);
//	StringCchCat(str, strLength, TEXT(" "));
//	int len = _tcslen(str);
//	::GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, 
//		&st, NULL, &str[len], strLength - len);
//}

// poom date
/*void _printPoomDate(TCHAR * str, int strLength, FILETIME ft) {
	SYSTEMTIME st;
	FILETIME ftLocal;  //ajigee 4/25
	//FileTimeToSystemTime(&ft, &st); allelimo
	FileTimeToLocalFileTime(&ft, &ftLocal);
	FileTimeToSystemTime(&ftLocal, &st);

	::GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
		NULL, str, strLength);
	StringCchCat(str, strLength, TEXT(" "));
	int len = _tcslen(str);
	::GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, 
		&st, NULL, &str[len], strLength - len);
}*/

//FILETIME _poomDateToLocal(DATE poomDate) {
//	FILETIME ft;
//	SYSTEMTIME st;
//
//	VariantTimeToSystemTime(poomDate, &st);
//	SystemTimeToFileTime(&st, &ft);
//	return ft; 
//}

//void _printPoomDate2(TCHAR * str, int strLength, FILETIME ft) {
//	SYSTEMTIME st;
//	FILETIME ftLocal;  //ajigee 4/25
//	//FileTimeToSystemTime(&ft, &st); allelimo
//	FileTimeToLocalFileTime(&ft, &ftLocal);
//	FileTimeToSystemTime(&ftLocal, &st);
//	::GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
//		NULL, str, strLength);
//}
//void _printPoomDate3(TCHAR * str, int strLength, SYSTEMTIME st) {  //ajige 4/30
//	//SYSTEMTIME st;
//	//FILETIME ftLocal;  //ajigee 4/25
//	//FileTimeToSystemTime(&ft, &st); allelimo
//	//FileTimeToLocalFileTime(&ft, &ftLocal);
//	//FileTimeToSystemTime(&ftLocal, &st);
//	::GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
//		NULL, str, strLength);
//}

//void _printPoomHour2(TCHAR * str, int strLength, FILETIME ft) {
//	SYSTEMTIME st;
//
//		//FILETIME ftLocal;  //ajigee 4/25, no gets messed up
//	FileTimeToSystemTime(&ft, &st); //allelimo
//		//FileTimeToLocalFileTime(&ft, &ftLocal);
//		//FileTimeToSystemTime(&ftLocal, &st);
//
//	StringCchCopy(str, strLength, TEXT(""));
//	int len = _tcslen(str);
//	::GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, 
//		&st, NULL, &str[len], strLength - len);
//}

void OpenURL(const TCHAR * url) {
	SHELLEXECUTEINFO ShExecInfo = {0};

	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb = TEXT("open");
	ShExecInfo.lpFile = url;
	ShExecInfo.lpParameters = NULL;

	ShExecInfo.lpDirectory = NULL;
	ShExecInfo.nShow = SW_SHOW;
	ShExecInfo.hInstApp = NULL; 

	ShellExecuteEx(&ShExecInfo);
}
//ajige 3/31/10 run setting instead
/*void RunDialer() {
	PROCESS_INFORMATION pi;
	TCHAR szDialerPath[MAX_PATH];

	if (GetIDialerFilename(szDialerPath)) {
		CreateProcess(szDialerPath, NULL,
			NULL, NULL, FALSE, NULL, NULL, NULL, NULL, &pi);
	}

	else {
		CreateProcess(TEXT("cprog.exe"), NULL, 
			NULL, NULL, FALSE, NULL, NULL, NULL, NULL, &pi);
	}
}*/

//ajige 3/31/10
void RunSettings() {
	PROCESS_INFORMATION pi;
	bSet=true;
	TCHAR szISettingsPath[MAX_PATH];
		//MessageBox(0, L"RunSettings", L"Hei", 0);
	GetCurDirFilename(szISettingsPath, TEXT("Settings.exe"));
			//GetISettingsFilename(L"iAgenda.exe");
			//if (GetISettingsFilename(szISettingsPath)) {
	
	CreateProcess(szISettingsPath, NULL,
			NULL, NULL, FALSE, NULL, NULL, NULL, NULL, &pi);
			//MessageBox(0, szISettingsPath, L"Hei", 0);
	//}	

	//else
	//{
		//open outlook contacts
	//	CreateProcess(TEXT("\My Documents\Settings.exe"),NULL,
	//		NULL, NULL, FALSE, NULL, NULL, NULL, NULL, &pi);
	//}
}


// convert the SystemTime to poom localized VariantDate
// systemtime -> filetime -> localefiletime -> localesystemtime -> locale poom variantdate
// I can't find a quicker way to do this... :)
UINT _SystemToPoomInt()
{
	SYSTEMTIME stNow, stLocalNow;
	FILETIME ftNow, ftLocalNow;
	DATE dtLocalNow;

	GetSystemTime(&stNow);
	SystemTimeToFileTime(&stNow, &ftNow);
	FileTimeToLocalFileTime(&ftNow, &ftLocalNow);
	FileTimeToSystemTime(&ftLocalNow, &stLocalNow);
	SystemTimeToVariantTime(&stLocalNow, &dtLocalNow);

	return (UINT)dtLocalNow;
}

//DATE _SystemToPoomDate(SYSTEMTIME stNow)
//{
//	SYSTEMTIME stLocalNow;
//	FILETIME ftNow, ftLocalNow;
//	DATE dtLocalNow;
//
//	SystemTimeToFileTime(&stNow, &ftNow);
//	FileTimeToLocalFileTime(&ftNow, &ftLocalNow);
//	FileTimeToSystemTime(&ftLocalNow, &stLocalNow);
//	SystemTimeToVariantTime(&stLocalNow, &dtLocalNow);
//
//	return dtLocalNow;
//
//}

//UINT _SystemToPoomDateInt(SYSTEMTIME stNow)
//{
//	SYSTEMTIME stLocalNow;
//	FILETIME ftNow, ftLocalNow;
//	DATE dtLocalNow;
//
//	SystemTimeToFileTime(&stNow, &ftNow);
//	FileTimeToLocalFileTime(&ftNow, &ftLocalNow);
//	FileTimeToSystemTime(&ftLocalNow, &stLocalNow);
//	SystemTimeToVariantTime(&stLocalNow, &dtLocalNow);
//
//	return (UINT)dtLocalNow;
//
//}


// convert the poom VariantDate to localized VariantDate
// variant date -> systemtime -> filetime -> localefiletime -> localesystemtime -> locale poom variantdate
//UINT _PoomToInt(DATE dtPoomDate)
//{
//	FILETIME ftDate, ftLocalDate;
//	SYSTEMTIME stDate, stLocalDate;
//	DATE dtLocalDate;
//
//	VariantTimeToSystemTime(dtPoomDate, &stDate);
//	SystemTimeToFileTime(&stDate, &ftDate);
//	FileTimeToLocalFileTime(&ftDate, &ftLocalDate);
//	FileTimeToSystemTime(&ftLocalDate, &stLocalDate);
//	SystemTimeToVariantTime(&stLocalDate, &dtLocalDate);
//
//	return (UINT)dtLocalDate;
//}
//
//void _printHour(TCHAR * str, int strLength, SYSTEMTIME st) {  
//	
//	GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st,
//		NULL, str, strLength);
//}

void _printHour(TCHAR * str, int strLength, DATE datestart) {  

	SYSTEMTIME st;
	VariantTimeToSystemTime(datestart, &st);
	GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st,
		NULL, str, strLength);
}

void _printDate(TCHAR * str, int strLength, DATE datestart) {  

	SYSTEMTIME st;
	VariantTimeToSystemTime(datestart, &st);
	GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
		NULL, str, strLength);
}

//day of the week, fullname
//GetDateFormat(LOCALE_USER_DEFAULT, 0, &st,
//	TEXT("Dddd"), str, strLenght);